package gzhaoku.com.common.util;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ThreadUtils;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import cz.msebera.android.httpclient.Header;
import gzhaoku.com.common.Logger;

/**
 * APP升级
 */
public class AppUpdate {

    static final Logger log = Logger.getLog(AppUpdate.class);

    static boolean isMute = false;


    /**
     * 检查升级
     * @return
     */
    public static int checkUpdate(final Activity context){
        boolean r  = Api.checkVersion(context, new JsonHttpResponseHandler(){
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                log.i("[API<-]"+response.toString());
                try{
                    //判断版本号
                    int currVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
                    String currVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

                    com.alibaba.fastjson.JSONObject responseData = JSON.parseObject(response.toString());
                    String latestVersion = responseData.getString("version");
                    int latestBuild = Integer.parseInt(responseData.getString("build"));

                    if(StringUtils.equalsIgnoreCase(latestVersion, currVersion)){//版本一致
                        log.i("App Version is up to date.");

                        toast(context, "该版本已为最新");

                    }else{//版本不一致


                        if(latestBuild == currVersionCode){
                            toast(context, "该版本已为最新");
                        }else if(latestBuild < currVersionCode){
                            toast(context, "线上版本过旧，暂不更新");
                        }else{
                            //下载apk
                            toast(context, "检测到更新，下载中...");

                            //执行升级
                            new Thread(new ApkDownloader(context, responseData.getString("url"), latestVersion)).start();
                        }
                    }
                }catch (Exception e){
                    log.e(e);
                }

            }

        });
        return 1;
    }

    private static void toast(final Activity context, final String msg){
        if(isMute){
            return;
        }

        isMute = true;
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    static class ApkDownloader implements Runnable{

        Activity context;

        String apkLink;

        String versionName;

        public ApkDownloader(Activity context, String apkLink, String versionName) {
            this.context = context;
            this.apkLink = apkLink;
            this.versionName = versionName;
        }

        @Override
        public void run() {
            File r = null;
            while(r == null){

                r = new HttpDownloader().downloadFile(apkLink, "apk", versionName+".apk");

                if(r == null){
                    log.w("Failed to download apk:"+apkLink);
                }

                try {

                    Thread.sleep(3 * 1000l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            ApkInstaller.install(context,
                    r.getAbsolutePath());
        }
    }

}
